package cc.telecomdigital.tdstock.trading;

import java.util.ArrayList;
import java.util.List;

import com.lightstreamer.ls_client.UpdateInfo;

import cc.telecomdigital.tdstock.CommonDefn;
import cc.telecomdigital.tdstock.R;
import cc.telecomdigital.tdstock.Framework.Application_Framework.LS_ItemRequestType;
import cc.telecomdigital.tdstock.Framework.UniqueItem.DeviceInfo;
import cc.telecomdigital.tdstock.Framework.UniqueItem.TDStockLog;
import cc.telecomdigital.tdstock.Services.CommunicTools;
import cc.telecomdigital.tdstock.Services.LS_SubscriptionItem;
import cc.telecomdigital.tdstock.Services.LS_UserClient.CONNECTION_STATUS;
import cc.telecomdigital.tdstock.Services.LS_UserClient.ILS_UserClient_Authentication_Report;
import cc.telecomdigital.tdstock.Services.LS_UserClient.ILS_UserClient_Response;
import cc.telecomdigital.tdstock.Services.LS_UserClient.LS_UserClient_Authentication_Result;
import cc.telecomdigital.tdstock.activity.RealtimeStockActivity;

import cc.telecomdigital.tdstock.trading.Common.Trade_AppConstant;
import cc.telecomdigital.tdstock.trading.Common.Trade_StockReqOrderItem;
import cc.telecomdigital.tdstock.trading.Common.Trade_StockViewInfoItem;
import cc.telecomdigital.tdstock.trading.Common.Trade_StockViewInfoItem.StockPriceDiffFormat;
import cc.telecomdigital.tdstock.trading.Services.TradeAppInfo;
import cc.telecomdigital.tdstock.trading.Services.TradeGetStockQuote;
import cc.telecomdigital.tdstock.trading.Services.TradeOrderPlace;
import cc.telecomdigital.tdstock.trading.Services.TradeGetDetailStockQuote.ITradeGetStockQuoteResponse;
import cc.telecomdigital.tdstock.trading.Services.TradeGetDetailStockQuote.TradeGetStockQuoteResult;
import cc.telecomdigital.tdstock.trading.Services.TradeOrderPlace.ITradeOrderPlaceResponse;
import cc.telecomdigital.tdstock.trading.Services.TradeOrderPlace.TradeOrderPlaceResult;
import cc.telecomdigital.tdstock.trading.Tools.Trade_StockFunctionTools;
import cc.telecomdigital.tdstock.trading.Tools.ListGeneratorHelper;
import cc.telecomdigital.tdstock.trading.Tools.ViewCtrlHelper;
import cc.telecomdigital.tdstock.trading.widget.AppDialogOK;
import cc.telecomdigital.tdstock.trading.widget.InfoWheelAdapter;
import cc.telecomdigital.tdstock.trading.widget.WheelView;
import cc.telecomdigital.tdstock.trading.widget.AppDialogOK.IAppDialogOK;

import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.os.Handler;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RadioButton;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ViewFlipper;
import android.text.InputFilter;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager.LayoutParams;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.Animation.AnimationListener;
import android.view.inputmethod.EditorInfo;

public class Trade_OrderKeypadActivity extends Trade_TemplateActivity implements
	View.OnClickListener, ILS_UserClient_Response
{
	// The none is consider as price
	private enum TRANSITEM_FOCUS
	{
		PRICE, QUANTITY
	}

	private WheelView						stockWheelView;
	private InfoWheelAdapter					stockWheelAdapter;
	private List<String>					priceRange;
	private List<String>					quantityRange;
	private WheelView.IOnWheelScrollListener	scrollListener;
	private View.OnClickListener				transactionInfoListener;
	private View.OnClickListener				stockKeyboardListener;
	private CheckBox.OnCheckedChangeListener	transactionInfoStateListener;
	private Handler                              UIHandler = new Handler();
	// Local activity class as an object
	// Buy sell flipper
	private ViewFlipper						viewFlipObj;

	private final int						invokeTimeDelay	= 200;

	private TRANSITEM_FOCUS					transFocus;
	private Trade_StockViewInfoItem			curStockInfo;
	private Trade_StockReqOrderItem			orderStockInfo;
	
	@Override
	public void onCreate(Bundle iSaveInstance)
	{
		super.onCreate(iSaveInstance);
		// With banner consider as a different layout, with different user
		// experience
		setContentView(R.layout.stocktrade_keypad);

		// This page is gain to be set to view as PORTRAIT only, no rotational
		// changes
		setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

		findViewById(R.id.view_stocktrade_keypad_header_Home)
				.setOnClickListener(this);
		// Map the button function
		// Set Header as UserName
		Button tmpButton = (Button) findViewById(R.id.view_stocktrade_keypad_header_Title);
		
		//Have the button ready to be pressed
		if (TradeAppInfo.TradeKeySwap_Ready)
		{
			tmpButton.setClickable(true);
			tmpButton.setOnClickListener(this);
			tmpButton.setBackgroundDrawable(getResources().getDrawable(R.drawable.at_top_tradestock_label));
		}
//		else
//			tmpButton.setText(TradeAppInfo.GetUserName());

		// Flipper UI
		viewFlipObj = (ViewFlipper) findViewById(R.id.stocktrade_keypad_OrderFlipper);

		InitViewComponent();

		// Reset the button state
		// Button enterButton;
		//
		// enterButton =
		// (Button)findViewById(R.id.view_stocktrade_keypad_Enter);
		// enterButton.setText(R.string.stockBuyText);
		// enterButton.setBackgroundDrawable(getResources().getDrawable(R.drawable.at_keypad_but_hugebuy));

		Intent                  intentObj;
		Trade_StockReqOrderItem requestItem;

		intentObj    = getIntent();
		requestItem  = null;
		curStockInfo = null;
		if (intentObj != null)
		{
			requestItem  = intentObj.getParcelableExtra(Trade_AppConstant.stockOrderRequestInfo);
			curStockInfo = intentObj.getParcelableExtra(Trade_AppConstant.stockViewInfo);
		}
		
		InitRequestOrderItem(requestItem);
		
		// Set the UI Title		
		SetStockTitleUpdate(orderStockInfo.stockCode, orderStockInfo.chnName,
						orderStockInfo.engName);		
		
		// Update the CurStock Information		
		InitCurrentStockInfo(curStockInfo);
		
		ImageButton imgButton;

		imgButton = (ImageButton)findViewById(R.id.view_stocktrade_keypad_header_informer);		
		if (TradeAppInfo.IsDemoAccount())
		{
			imgButton.setImageDrawable(getResources().getDrawable(R.drawable.at_stocktrade_keypad_networksignal));			
			imgButton.setClickable(false);				
			imgButton.setEnabled(true);
		}
		else
		{
			CONNECTION_STATUS lsStatus;
			boolean 		   isConnected;

			if (TradeAppInfo.IsBMPMode())
			{
				imgButton.setImageDrawable(getResources().getDrawable(R.drawable.ic_menu_refresh));
				imgButton.setClickable(true);					
				imgButton.setOnClickListener(this);
				imgButton.setEnabled(true);
			}
			else
			{
				imgButton.setImageDrawable(getResources().getDrawable(R.drawable.at_stocktrade_keypad_networksignal));
				imgButton.setClickable(false);					
				lsStatus = appHost.LSClient_GetLastConnectionStatus();
				if (lsStatus == CONNECTION_STATUS.CONNECTED)
					isConnected = true;
				else
					isConnected = false;
		
			     imgButton.setEnabled(isConnected);				
			}				
		}		
	}

	
	@Override
	protected void onNewIntent(Intent intentObj)
	{
		Trade_StockReqOrderItem requestItem;

		requestItem  = null;
		curStockInfo = null;
		if (intentObj != null)
		{
			requestItem  = intentObj.getParcelableExtra(Trade_AppConstant.stockOrderRequestInfo);
			curStockInfo = intentObj.getParcelableExtra(Trade_AppConstant.stockViewInfo);
		}
		
		InitRequestOrderItem(requestItem);
		
		// Set the UI Title		
		SetStockTitleUpdate(orderStockInfo.stockCode, orderStockInfo.chnName,
						orderStockInfo.engName);		
		
		// Update the CurStock Information		
		InitCurrentStockInfo(curStockInfo);		
	}
	
	@Override
	public void onResume()
	{
		super.onResume();
		//If we have set it once and the status is success, the resume will resume the process
		//and there is no need for us to do
		if (!TradeAppInfo.IsDemoAccount() && !TradeAppInfo.IsBMPMode())
		{
			if (_activityController.IsDestroyOnFinish() == false)
			{
				if  (curStockInfo != null)
					SubscribeViewingStock(Trade_StockFunctionTools.RemoveStockCodeFormat(curStockInfo.stockCode));
			}
			else
			{
				if ((reqIDString == null) && (curStockInfo != null))
					SubscribeViewingStock(Trade_StockFunctionTools.RemoveStockCodeFormat(curStockInfo.stockCode));
			}
		}	
	}
	
	@Override
	public void onPause()
	{
		if (toastDisplay != null)
			toastDisplay.cancel();		
		// Close our keyboard if possible
		FlipToKeyPadEntry();
		DetachedDisconnectMessage();		
		super.onPause();
	}

	static Toast toastDisplay = null;
	public void UpdateToast(String iText)
	{
		// Toast String
			
		if (toastDisplay != null)
		{
			toastDisplay.cancel();
			toastDisplay.setText(iText);
		}
		else
			toastDisplay = Toast.makeText(actContext, iText, Toast.LENGTH_SHORT);
		toastDisplay.show();
	}		
		
	private boolean isStockRequestStart = false; 	
	
	@Override
	public void onClick(View iViewObj)
	{
		int objID;

		objID = iViewObj.getId();
		switch (objID)
		{
			case R.id.view_stocktrade_keypad_header_Home:
				SwitchFreeActivity(Trade_tradingOptionActivity.class);
				break;
			case R.id.view_stocktrade_keypad_header_informer:
				//Prevent it's click again
				if (isStockRequestStart == true)
					break;
				if (curStockInfo.stockCode != null)
					StockQuoteRequest(Trade_StockFunctionTools.FormatFullStockCode(curStockInfo.stockCode));
				break;
			case R.id.view_stocktrade_keypad_header_Title:
				/* Switching to the real time data */	
				{
					SharedPreferences.Editor editor;
					String                   strCode;
					int                      codeNum;

					codeNum = Integer.valueOf(curStockInfo.stockCode);
					strCode = String.valueOf(codeNum);
					editor = getSharedPreferences( CommonDefn.SYSTEM_CURRENT_SETTING,
									           Context.MODE_PRIVATE).edit();
					editor.putString( CommonDefn.PREFERENCE_STOCK_CODE, strCode);
					editor.commit();
				}					
				RealtimeStockActivity.SetTabIndex(RealtimeStockActivity.TAB_INDEX_STOCK);
				SwitchFreeActivity(RealtimeStockActivity.class);					
				break;
		}
	}

	private void InitRequestOrderItem(Trade_StockReqOrderItem iRequestItem)
	{
		TextView                textViewObj;
		int                     textColor;
		String                  signText;

		// Should not happen, the program will be confused
		if (iRequestItem == null)
		{
			orderStockInfo = new Trade_StockReqOrderItem("", "", "");
			orderStockInfo.SetOrderSide(Trade_StockReqOrderItem.TRANSACTIONTYPE_BID);
		}
		else
		{
			// First Fill in the import info
			orderStockInfo = new Trade_StockReqOrderItem(iRequestItem);
			// Prepare the price info page
			((CheckBox) findViewById(R.id.view_stocktrade_keypad_orderinfo_ProcessQuantity))
					.setText(orderStockInfo.getOutStandingQuantityText());
			((CheckBox) findViewById(R.id.view_stocktrade_keypad_orderinfo_ProcessPrice))
					.setText(orderStockInfo.getPiceText());
			((TextView) findViewById(R.id.view_stocktrade_keypad_orderinfo_ProcessAmount))
					.setText(orderStockInfo.getTotalText());
		}
		
		if (orderStockInfo.GetCurrencyCode().equals(TradeAppInfo.CNYCode))
		{
			signText = TradeAppInfo.CNYSign;
			textColor = getResources().getColor(R.color.DimYellow);
		}
		else if (orderStockInfo.GetCurrencyCode().equals(TradeAppInfo.USDCode))
		{
			signText = TradeAppInfo.USDSign;
			textColor = getResources().getColor(R.color.DimYellow);
		}
		else
		{
			signText = TradeAppInfo.HKDSign;
			textColor = getResources().getColor(R.color.White);
		}
		
		//Set the CurrentInfo
		orderStockInfo.SetCurrencyCode(iRequestItem.GetCurrencyCode());
		textViewObj = (TextView)findViewById(R.id.view_stocktrade_keypad_orderinfo_ProcessSign);
		textViewObj.setText(signText);
		textViewObj.setTextColor(textColor);
		
		textViewObj = (TextView)findViewById(R.id.view_stocktrade_keypad_orderinfo_ProcessAmountSign);
		textViewObj.setText(signText);
		textViewObj.setTextColor(textColor);
		
		textViewObj = (TextView)findViewById(R.id.view_stocktrade_keypad_orderinfo_ProcessAmount);
		textViewObj.setTextColor(textColor);
		
		textViewObj = (TextView)findViewById(R.id.view_stocktrade_keypad_orderinfo_ProcessPrice);
		textViewObj.setTextColor(textColor);				
		
		
		Button enterButton;

		enterButton = (Button) findViewById(R.id.view_stocktrade_keypad_Enter);
		// Prepare the curLineInfo, and set the text on Display
		if (orderStockInfo.getOrderSide().equals(Trade_StockReqOrderItem.TRANSACTIONTYPE_BID))
		{
			((RadioButton) findViewById(R.id.view_stocktrade_keypad_priceinfo_OptionBuy))
					.setChecked(true);
			((TextView) findViewById(R.id.view_stocktrade_keypad_orderinfo_ProcessText))
					.setText(R.string.stockBuyText);
			enterButton.setBackgroundDrawable(getResources().getDrawable(
					R.drawable.at_keypad_but_hugebuy));
			enterButton.setText(R.string.stockBuyText);
		}
		else
		{
			((RadioButton) findViewById(R.id.view_stocktrade_keypad_priceinfo_OptionSell))
					.setChecked(true);
			((TextView) findViewById(R.id.view_stocktrade_keypad_orderinfo_ProcessText))
					.setText(R.string.stockSellText);
			enterButton.setBackgroundDrawable(getResources().getDrawable(
					R.drawable.at_keypad_but_hugesell));
			enterButton.setText(R.string.stockSellText);
		}
	}

	private void InitCurrentStockInfo(Trade_StockViewInfoItem iStockItem)
	{
		if (iStockItem == null)
			return;
		
		// This is for the viewing Start
		// Set to the top display
		SetStockCurBidAsk(iStockItem);
		UpdateStockPriceUI(iStockItem, false);

		CreatePriceRange(iStockItem.GetCurPriceText(), iStockItem.stepPrice);		

		transFocus = TRANSITEM_FOCUS.PRICE;
		stockWheelAdapter.InitItemList(priceRange);

		// Set Position on the wheel
		int pos;
		
		if (orderStockInfo.price == null || orderStockInfo.price.equals(""))
			pos = priceRange.size()/2;
		else
		{
			String formatPrice;
			
			formatPrice = Trade_StockFunctionTools.AutoFillInDecimal(orderStockInfo.price, Trade_AppConstant.priceValueStringWithDec);		
			pos = ListGeneratorHelper.GetValueLocation(priceRange, formatPrice);
		}			
		stockWheelView.setCurrentItem(pos);

		CreateVolumeRange(iStockItem.stepVolume);
	}

	private void UpdateStockPriceUI(Trade_StockViewInfoItem iStockItem, boolean iBlinkEnable)
	{
		int penColorId;
		String convertString;
		TextView textViewObj;

		// Check if it is negative
		if (iStockItem.IsDropped())
			penColorId = getResources().getColor(R.color.Red);
		else
			penColorId = getResources().getColor(R.color.Green);

		textViewObj = (TextView) findViewById(R.id.view_stocktrade_keypad_priceinfo_CurPrice);
		textViewObj.setTextColor(penColorId);
		convertString = iStockItem.GetCurPriceText();
		textViewObj.setText(convertString);

		textViewObj = (TextView) findViewById(R.id.view_stocktrade_keypad_priceinfo_CurDiff);
		textViewObj.setTextColor(penColorId);
		textViewObj.setText(iStockItem.GetPriceDifferenceText(StockPriceDiffFormat.FULL));

		if (iBlinkEnable)
			BlinkPriceInfo();
	}

	private void SetStockCurBidAsk(Trade_StockViewInfoItem iStockItem)
	{		
		String convertString;

		convertString = iStockItem.GetCurBidPriceText();
		((RadioButton) findViewById(R.id.view_stocktrade_keypad_priceinfo_OptionBuy))
				.setText(convertString);
	
		convertString = iStockItem.GetCurAskPriceText();
		((RadioButton) findViewById(R.id.view_stocktrade_keypad_priceinfo_OptionSell))
				.setText(convertString);
	}

	private void CreatePriceRange(String iStartPrice, String iStepPrice)
	{
		priceRange.clear();
		if (iStartPrice != null)
		{
			priceRange.addAll(ListGeneratorHelper.CreatePriceRangeList(
					iStartPrice, iStepPrice,
					Trade_AppConstant.maxChoiceForPriceCeiling,
					Trade_AppConstant.maxChoiceForPriceFloor));
		}
	}

	private void CreateVolumeRange(String iStartVol)
	{
		quantityRange.clear();
		quantityRange.addAll(ListGeneratorHelper.CreateQuantityRangeTextList(
				iStartVol,
				Trade_AppConstant.maxChoiceForQuantity));
	}

	boolean	keyboardFirstEntry;

	/* Only UI component construction */
	private void InitViewComponent()
	{
		RadioButton tmpRadio;
		CheckBox tmpCheck;

		keyboardFirstEntry = false;
		stockWheelView = (WheelView) findViewById(R.id.view_stocktrade_keypad_orderinfo_InfoWheel);

		priceRange = new ArrayList<String>();
		quantityRange = new ArrayList<String>();

		// When first comes in the focus is always on price
		stockWheelAdapter = new InfoWheelAdapter(this, priceRange, -1, 20);
		stockWheelView.setViewAdapter(stockWheelAdapter);

		scrollListener = new WheelView.IOnWheelScrollListener()
		{
			@Override
			public void onScrollingFinished(WheelView iWheel)
			{
				int index;
				String tmpString;
				CheckBox chkBox;

				// After the scroll, the highlight is always off
				SetCheckBoxState(R.id.view_stocktrade_keypad_orderinfo_ProcessQuantity,
						false);
				SetCheckBoxState(R.id.view_stocktrade_keypad_orderinfo_ProcessPrice,
						false);

				index = iWheel.getCurrentItemIndex();
				if (transFocus == TRANSITEM_FOCUS.QUANTITY)
				{
					if (quantityRange.size() <= 0)
						return;

					// Wheel provides a valid argument
					tmpString = quantityRange.get(index);
					orderStockInfo.SetOutStandingOrderQuantity(tmpString);

					chkBox = (CheckBox) findViewById(R.id.view_stocktrade_keypad_orderinfo_ProcessQuantity);
					chkBox.setText(orderStockInfo
							.getOutStandingQuantityText());
					// Also display the total if possible
					tmpString = orderStockInfo.getTotalText();
					((TextView) findViewById(R.id.view_stocktrade_keypad_orderinfo_ProcessAmount))
							.setText(tmpString);

					// Set a shot of green blash for the text
					chkBox.setTextColor(actContext.getResources()
							.getColor(R.color.Green));
					Animation animatAction = AnimationUtils.loadAnimation(
							actContext, R.anim.just_delay);
					animatAction.setDuration(invokeTimeDelay);
					animatAction
							.setAnimationListener(new AnimationListener()
							{
								@Override
								public void onAnimationEnd(
										Animation animation)
								{
									CheckBox chkBox;

									chkBox = (CheckBox) findViewById(R.id.view_stocktrade_keypad_orderinfo_ProcessQuantity);
									chkBox.setTextColor(actContext
											.getResources()
											.getColor(R.color.White));
								}

								@Override
								public void onAnimationRepeat(
										Animation animation)
								{	}

								@Override
								public void onAnimationStart(
										Animation animation)
								{	}
							});
					chkBox.startAnimation(animatAction);

				}
				else
				{
					if (priceRange.size() <= 0)
						return;

					// Wheel provides a valid argument
					tmpString = priceRange.get(index);
					orderStockInfo.SetOrderPrice(tmpString);
					chkBox = (CheckBox) findViewById(R.id.view_stocktrade_keypad_orderinfo_ProcessPrice);
					chkBox.setText(orderStockInfo.getPiceText());
					// Also display the total if possible
					tmpString = orderStockInfo.getTotalText();
					((TextView) findViewById(R.id.view_stocktrade_keypad_orderinfo_ProcessAmount))
							.setText(tmpString);

					// Set a shot of green blash for the text
					chkBox.setTextColor(actContext.getResources()
							.getColor(R.color.Green));
					Animation animatAction = AnimationUtils.loadAnimation(
							actContext, R.anim.just_delay);
					animatAction.setDuration(invokeTimeDelay);
					animatAction
							.setAnimationListener(new AnimationListener()
							{
								@Override
								public void onAnimationEnd(
										Animation animation)
								{
									int      textColor;
									CheckBox chkBox;

									chkBox = (CheckBox) findViewById(R.id.view_stocktrade_keypad_orderinfo_ProcessPrice);
									if (orderStockInfo.GetCurrencyCode().equals(TradeAppInfo.CNYCode))
										textColor = getResources().getColor(R.color.DimYellow);
									else if (orderStockInfo.GetCurrencyCode().equals(TradeAppInfo.USDCode))
										textColor = getResources().getColor(R.color.DimYellow);
									else
										textColor = getResources().getColor(R.color.White);
									chkBox.setTextColor(textColor);
								}

								@Override
								public void onAnimationRepeat(Animation animation)
								{	}

								@Override
								public void onAnimationStart(Animation animation)
								{	}
							});
					chkBox.startAnimation(animatAction);
				}
			}

			@Override
			public void onScrollingStarted(WheelView iWheel)
			{	}
		};
		stockWheelView.addScrollingListener(scrollListener);

		transactionInfoListener = new View.OnClickListener()
		{
			@Override
			public void onClick(View iViewObj)
			{
				String tmpString;

				switch (iViewObj.getId())
				{
					case R.id.view_stocktrade_keypad_orderinfo_ProcessPrice:
						if (transFocus != TRANSITEM_FOCUS.PRICE)
						{
							transFocus = TRANSITEM_FOCUS.PRICE;
							stockWheelView.invalidateWheel(true);
							stockWheelAdapter.ChangeItemList(priceRange);
						}
						// Try to auto roll to the selection
						{
							int pos;

							pos = ListGeneratorHelper.GetValueLocation(
									priceRange, orderStockInfo.price);
							stockWheelView.setCurrentItem(pos);
						}
						break;

					case R.id.view_stocktrade_keypad_orderinfo_ProcessQuantity:
						if (transFocus != TRANSITEM_FOCUS.QUANTITY)
						{
							transFocus = TRANSITEM_FOCUS.QUANTITY;
							stockWheelView.invalidateWheel(true);
							stockWheelAdapter
									.ChangeItemList(quantityRange);
						}

						// Try to auto roll to the selection
						{
							int pos;

							pos = ListGeneratorHelper
									.GetValueLocation(
											quantityRange,
											orderStockInfo.outStandingQuantity);
							stockWheelView.setCurrentItem(pos);
						}
						break;

					case R.id.view_stocktrade_keypad_priceinfo_OptionBuy:
						SetCheckBoxState(R.id.view_stocktrade_keypad_orderinfo_ProcessQuantity,
								false);
						SetCheckBoxState(R.id.view_stocktrade_keypad_orderinfo_ProcessPrice,
								false);
						SetRadioButtonState(R.id.view_stocktrade_keypad_priceinfo_OptionBuy,
								true);
						SetRadioButtonState(R.id.view_stocktrade_keypad_priceinfo_OptionSell,
								false);
						// The transaction type text
						((TextView) findViewById(R.id.view_stocktrade_keypad_orderinfo_ProcessText))
								.setText(R.string.stockBuyText);
						orderStockInfo.SetOrderSide(Trade_StockReqOrderItem.TRANSACTIONTYPE_BID);
						if (transFocus != TRANSITEM_FOCUS.PRICE)
						{
							transFocus = TRANSITEM_FOCUS.PRICE;
							stockWheelView.invalidateWheel(true);
							stockWheelAdapter.ChangeItemList(priceRange);
						}

						// Get the sell price and assign to the process
						// Process
						tmpString = curStockInfo.GetCurAskPriceText();
						if (tmpString.equals(""))
							break;

						orderStockInfo.SetOrderPrice(tmpString);
						tmpString = Trade_StockFunctionTools
								.AddFormatToThousand(tmpString);
						((CheckBox) findViewById(R.id.view_stocktrade_keypad_orderinfo_ProcessPrice))
								.setText(tmpString);
						// Also calculate the difference
						tmpString = orderStockInfo.getTotalText();
						((TextView) findViewById(R.id.view_stocktrade_keypad_orderinfo_ProcessAmount))
								.setText(tmpString);
						{
							// Now change the Buy/Sell Button look
							Button button;

							button = (Button) findViewById(R.id.view_stocktrade_keypad_Enter);
							button.setBackgroundDrawable(getResources()
									.getDrawable(
											R.drawable.at_keypad_but_hugebuy));
							button.setText(R.string.stockBuyText);
						}
						break;

					case R.id.view_stocktrade_keypad_priceinfo_OptionSell:
						SetCheckBoxState(
								R.id.view_stocktrade_keypad_orderinfo_ProcessQuantity,
								false);
						SetCheckBoxState(
								R.id.view_stocktrade_keypad_orderinfo_ProcessPrice,
								false);

						SetRadioButtonState(
								R.id.view_stocktrade_keypad_priceinfo_OptionBuy,
								false);
						SetRadioButtonState(
								R.id.view_stocktrade_keypad_priceinfo_OptionSell,
								true);
						// The transaction type text
						((TextView) findViewById(R.id.view_stocktrade_keypad_orderinfo_ProcessText))
								.setText(R.string.stockSellText);
						orderStockInfo.SetOrderSide(Trade_StockReqOrderItem.TRANSACTIONTYPE_ASK);
						if (transFocus != TRANSITEM_FOCUS.PRICE)
						{
							transFocus = TRANSITEM_FOCUS.PRICE;
							stockWheelView.invalidateWheel(true);
							stockWheelAdapter.ChangeItemList(priceRange);
						}

						// Get the sell price and assign to the process
						// Process
						tmpString = curStockInfo.GetCurBidPriceText();
						if (tmpString.equals(""))
							break;

						orderStockInfo.SetOrderPrice(tmpString);
						tmpString = Trade_StockFunctionTools
								.AddFormatToThousand(tmpString);
						((CheckBox) findViewById(R.id.view_stocktrade_keypad_orderinfo_ProcessPrice))
								.setText(tmpString);
						// Also calculate the difference
						tmpString = orderStockInfo.getTotalText();
						((TextView) findViewById(R.id.view_stocktrade_keypad_orderinfo_ProcessAmount))
								.setText(tmpString);
						{
							// Now change the Buy/Sell Button look
							Button button;

							button = (Button) findViewById(R.id.view_stocktrade_keypad_Enter);
							button.setBackgroundDrawable(getResources()
									.getDrawable(
											R.drawable.at_keypad_but_hugesell));
							button.setText(R.string.stockSellText);
						}
						break;
				}
			}
		};

		transactionInfoStateListener = new CheckBox.OnCheckedChangeListener()
		{
			// Only one view is allow to be shown, pretend to be a Radio
			// Button
			@Override
			public void onCheckedChanged(CompoundButton buttonView,
					boolean isChecked)
			{
				int objId;
				String tmpString;

				objId = buttonView.getId();

				switch (objId)
				{
					case R.id.view_stocktrade_keypad_orderinfo_ProcessPrice:
					case R.id.view_stocktrade_keypad_orderinfo_ProcessQuantity:
						if (isChecked == false)
						{
							tmpString = ((CheckBox) buttonView)
									.getText().toString();
							if ((tmpString == null)
									|| (tmpString.length() == 0))
								tmpString = "0";

							if (objId == R.id.view_stocktrade_keypad_orderinfo_ProcessQuantity)
								orderStockInfo
										.SetOutStandingOrderQuantity(tmpString);
							else
								orderStockInfo.SetOrderPrice(tmpString);

							((Button) findViewById(R.id.view_stocktrade_keypad_dot000))
									.setText(".");
							if (objId == R.id.view_stocktrade_keypad_orderinfo_ProcessPrice)
								tmpString = Trade_StockFunctionTools
										.AutoFillInDecimal(
												tmpString,
												Trade_AppConstant.priceValueStringWithDec);
							// Create the format
							tmpString = Trade_StockFunctionTools
									.AddFormatToThousand(tmpString);
							buttonView.setText(tmpString);
							tmpString = orderStockInfo.getTotalText();
							((TextView) findViewById(R.id.view_stocktrade_keypad_orderinfo_ProcessAmount))
									.setText(tmpString);
						}
						else
						{
							keyboardFirstEntry = true;
							// Kill the format
							tmpString = ((CheckBox) buttonView)
									.getText().toString();

							tmpString = tmpString.replace(",", "");
							buttonView.setText(tmpString);

							// Swap the state for the button
							if (objId == R.id.view_stocktrade_keypad_orderinfo_ProcessPrice)
								SetCheckBoxState(
										R.id.view_stocktrade_keypad_orderinfo_ProcessQuantity,
										false);
							else
							{
								SetCheckBoxState(
										R.id.view_stocktrade_keypad_orderinfo_ProcessPrice,
										false);
								((Button) findViewById(R.id.view_stocktrade_keypad_dot000))
										.setText("000");
							}
						}
						break;
				}
			}
		};

		// Only for keyboard entry
		stockKeyboardListener = new View.OnClickListener()
		{
			@Override
			public void onClick(View iViewObj)
			{
				int objId;
				String tmpString;
				CheckBox chkBox;
				TRANSITEM_FOCUS fCurFocus;

				objId = iViewObj.getId();
				// If both of them are not high light we could just kill the
				// focus
				fCurFocus = TRANSITEM_FOCUS.PRICE;
				chkBox = (CheckBox) findViewById(R.id.view_stocktrade_keypad_orderinfo_ProcessPrice);
				if (chkBox.isChecked() == false)
				{
					fCurFocus = TRANSITEM_FOCUS.QUANTITY;
					chkBox = (CheckBox) findViewById(R.id.view_stocktrade_keypad_orderinfo_ProcessQuantity);
				}
				if (chkBox.isChecked() == false)
					return;

				// Kill the text for the first empty
				if (keyboardFirstEntry == true)
				{
					keyboardFirstEntry = false;
					tmpString = "";
				}
				else
					tmpString = chkBox.getText().toString();

				if ((tmpString != null) && tmpString.length() != 0)
					tmpString = tmpString.replace(",", "");
				else
					tmpString = "";

				switch (objId)
				{
					case R.id.view_stocktrade_keypad_0:
						if (fCurFocus == TRANSITEM_FOCUS.QUANTITY)
						{
							if (tmpString.length() == 0)
								break;
						}
						else
						{
							if (tmpString.length() == 0)
							{
								tmpString = "0.";
								break;
							}
						}
						tmpString += "0";
						break;

					case R.id.view_stocktrade_keypad_1:
						tmpString += "1";
						break;
					case R.id.view_stocktrade_keypad_2:
						tmpString += "2";
						break;
					case R.id.view_stocktrade_keypad_3:
						tmpString += "3";
						break;
					case R.id.view_stocktrade_keypad_4:
						tmpString += "4";
						break;
					case R.id.view_stocktrade_keypad_5:
						tmpString += "5";
						break;
					case R.id.view_stocktrade_keypad_6:
						tmpString += "6";
						break;
					case R.id.view_stocktrade_keypad_7:
						tmpString += "7";
						break;
					case R.id.view_stocktrade_keypad_8:
						tmpString += "8";
						break;
					case R.id.view_stocktrade_keypad_9:
						tmpString += "9";
						break;

					case R.id.view_stocktrade_keypad_dot000:
						if (fCurFocus == TRANSITEM_FOCUS.QUANTITY)
						{
							if (tmpString.length() == 0)
								break;
							tmpString += "000";
						}
						else
						{
							if (tmpString.length() == 0)
								tmpString = "0";
							if (tmpString.contains("."))
								break;
							tmpString += ".";
						}
						break;
					case R.id.view_stocktrade_keypad_AC:
						tmpString = "";
						break;
					case R.id.view_stocktrade_keypad_Back:
						if (tmpString.length() <= 1)
						{
							tmpString = "";
							break;
						}
						tmpString = tmpString.substring(0,
								tmpString.length() - 1);
						break;
				}

				if (fCurFocus == TRANSITEM_FOCUS.QUANTITY)
				{
					// Exceed our restriction
					if (tmpString.length() > 7)
						return;
					orderStockInfo.SetOutStandingOrderQuantity(tmpString);
				}
				else
				{
					// Exceed our restriction
					if (tmpString.length() > Trade_AppConstant.priceValueStringWithDec)
						return;

					orderStockInfo.SetOrderPrice(tmpString);
				}

				chkBox.setText(tmpString);
				((TextView) findViewById(R.id.view_stocktrade_keypad_orderinfo_ProcessAmount))
						.setText(orderStockInfo.getTotalText());
			}
		};

		tmpCheck = (CheckBox) findViewById(R.id.view_stocktrade_keypad_orderinfo_ProcessPrice);
		tmpCheck.setOnClickListener(transactionInfoListener);
		tmpCheck.setOnCheckedChangeListener(transactionInfoStateListener);
		tmpCheck = (CheckBox) findViewById(R.id.view_stocktrade_keypad_orderinfo_ProcessQuantity);
		tmpCheck.setOnClickListener(transactionInfoListener);
		tmpCheck.setOnCheckedChangeListener(transactionInfoStateListener);

		tmpRadio = (RadioButton) findViewById(R.id.view_stocktrade_keypad_priceinfo_OptionBuy);
		tmpRadio.setOnClickListener(transactionInfoListener);
		tmpRadio = (RadioButton) findViewById(R.id.view_stocktrade_keypad_priceinfo_OptionSell);
		tmpRadio.setOnClickListener(transactionInfoListener);

		// CallBack for the keypad
		findViewById(R.id.view_stocktrade_keypad_0).setOnClickListener(
				stockKeyboardListener);
		findViewById(R.id.view_stocktrade_keypad_1).setOnClickListener(
				stockKeyboardListener);
		findViewById(R.id.view_stocktrade_keypad_2).setOnClickListener(
				stockKeyboardListener);
		findViewById(R.id.view_stocktrade_keypad_3).setOnClickListener(
				stockKeyboardListener);
		findViewById(R.id.view_stocktrade_keypad_4).setOnClickListener(
				stockKeyboardListener);
		findViewById(R.id.view_stocktrade_keypad_5).setOnClickListener(
				stockKeyboardListener);
		findViewById(R.id.view_stocktrade_keypad_6).setOnClickListener(
				stockKeyboardListener);
		findViewById(R.id.view_stocktrade_keypad_7).setOnClickListener(
				stockKeyboardListener);
		findViewById(R.id.view_stocktrade_keypad_8).setOnClickListener(
				stockKeyboardListener);
		findViewById(R.id.view_stocktrade_keypad_9).setOnClickListener(
				stockKeyboardListener);
		findViewById(R.id.view_stocktrade_keypad_dot000).setOnClickListener(
				stockKeyboardListener);
		findViewById(R.id.view_stocktrade_keypad_AC).setOnClickListener(
				stockKeyboardListener);
		findViewById(R.id.view_stocktrade_keypad_Back).setOnClickListener(
				stockKeyboardListener);
		findViewById(R.id.view_stocktrade_keypad_Enter).setOnClickListener(
				new View.OnClickListener()
				{
					@Override
					public void onClick(View v)
					{
						boolean valid;
						String priceText, quantityText;

						/* Turn off the edit mode */
						SetCheckBoxState(R.id.view_stocktrade_keypad_orderinfo_ProcessQuantity,
										false);
						SetCheckBoxState(R.id.view_stocktrade_keypad_orderinfo_ProcessPrice,
										false);						
						
						priceText = ((CheckBox) findViewById(R.id.view_stocktrade_keypad_orderinfo_ProcessPrice))
								.getText().toString();
						quantityText = ((CheckBox) findViewById(R.id.view_stocktrade_keypad_orderinfo_ProcessQuantity))
								.getText().toString();
						priceText = priceText.replace(",", "");
						priceText = Trade_StockFunctionTools
								.AutoFillInDecimal(
										priceText,
										Trade_AppConstant.priceValueStringWithDec);
						quantityText = quantityText.replace(",", "");
						
						valid = Trade_StockFunctionTools.ValidateStockTrade( priceText,quantityText,
																   curStockInfo.stepVolume);
						if (valid)
						{
							orderStockInfo
									.SetOutStandingOrderQuantity(quantityText);
							orderStockInfo.SetOrderPrice(priceText);
							FlipToConfirmationDisplay();
						}
						else
						{
							AppDialogOK curDialog;

							curDialog = new AppDialogOK(actContext);
							curDialog.SetTextContent(R.string.inputEntryErrorText);
							curDialog.show(null, true);
						}
					}
				});

		Button buttonObj;

		buttonObj = (Button) findViewById(R.id.view_stocktrade_keypad_confirminfo_Cancel);
		buttonObj.setOnClickListener(new Button.OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				FlipToKeyPadEntry();
			}
		});

		buttonObj = (Button) findViewById(R.id.view_stocktrade_keypad_confirminfo_Confirm);
		buttonObj.setOnClickListener(new Button.OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				if (isTradeOrderPlaceStart == true)
					return;
				SendTradePlaceOrder();
			}
		});

		// Set max character for password entry
		InputFilter[] FilterArray;

		FilterArray = new InputFilter[1];
		FilterArray[0] = new InputFilter.LengthFilter( Trade_AppConstant.maxPasswordLength);
		// Second view of the flipper
		EditText editTextObj;

		editTextObj = (EditText) findViewById(R.id.view_stocktrade_keypad_confirminfo_Password);
		editTextObj.setOnFocusChangeListener(_keyboardPopListener);
		editTextObj.setFilters(FilterArray);
		editTextObj.setOnEditorActionListener(new TextView.OnEditorActionListener()
		{
					@Override
					public boolean onEditorAction(TextView v, int actionId, KeyEvent event)
					{
						if (actionId == EditorInfo.IME_ACTION_DONE)
						{
							if (isTradeOrderPlaceStart == true)
								return true;							
							SendTradePlaceOrder();
							return true;
						}
						return false;
					}
		});
	}

	private boolean isTradeOrderPlaceStart = false;
	private void SendTradePlaceOrder()
	{
		String passwordString;
		EditText editTextObj;
		
		editTextObj = (EditText)findViewById(R.id.view_stocktrade_keypad_confirminfo_Password);
		passwordString = editTextObj.getText().toString();
		if (!CommunicTools.isASCIIString(passwordString))		
		{
			Animation animatAction = AnimationUtils.loadAnimation( actContext, R.anim.shake);
			animatAction.setDuration(300);
			editTextObj.startAnimation(animatAction);
			return;
		}
		
		HideKeyBoard();
		FlipToKeyPadEntry();
		
		if (TradeAppInfo.IsDemoAccount() == false)
		{
			if (IsNetworkAvailable() == false)
			{
				ShowPromptMessage(getString(R.string.commErrorText));
				return;
			}
	
			if (TradeAppInfo.HasSessionTimeExpired())
			{
				ShowTimeExpiredBox();
				return;
			}
		}

		ShowWaitingDialog();
		
		final TradeOrderPlace placeOrder;

		isTradeOrderPlaceStart = true;		
		placeOrder = new TradeOrderPlace(actContext, TradeAppInfo.GetUserName(), passwordString);
		placeOrder.SetPlaceOrder(orderStockInfo.stockCode,
				orderStockInfo.getOrderSide(), orderStockInfo.price,
				orderStockInfo.outStandingQuantity);

		placeOrder.SendRequest(TradeAppInfo.IsDemoAccount(),
				new ITradeOrderPlaceResponse()
				{
					@Override
					public void ResponseFunc(boolean iSuccessfulSend,
							TradeOrderPlaceResult iResponse)
					{
						isTradeOrderPlaceStart = false;
						if (iSuccessfulSend == false)
						{
							ShowPromptMessage(getString(R.string.commErrorText));
							return;
						}
						TradeAppInfo.ClearStockHistoryRecord();				
						HandlePlaceOrderResult(iResponse);
						placeOrder.Dispose();
					}
				});
	}

	private void CallBackToStockOrder()
	{
		Intent intentObj;

		intentObj = new Intent(this, Trade_AcctComboActivity.class);
		// Put something on the bundle to mark the current state
		intentObj.putExtra(Trade_AppConstant.tradingStateBundle, 0);
		//This is not a good method to switch, but we want this to happen
		//SwitchBackwardToTop(Trade_AcctComboActivity.class, intentObj);
		SwitchFreeActivity(Trade_AcctComboActivity.class, intentObj);
	}

	private void HandlePlaceOrderResult(TradeOrderPlaceResult iResult)
	{
		AppDialogOK promptDialog;

		promptDialog = null;
		if ((iResult.BrokerMessage != null)
				&& (iResult.BrokerMessage.length() != 0))
		{
			promptDialog = new AppDialogOK(this);
			promptDialog.SetTextContent(iResult.BrokerMessage);
			promptDialog.SetButtonText(R.string.okText);
			// return features are based on specification
		}

		// Login Session expired and kick user out to the login page
		if (iResult.StatusCode.equals("12"))
		{
			DismissWaitingDialog();
			// Back to the previous window, the trading option
			// Since the Window is call by Start With Result, we should end
			// with result
			if (promptDialog != null)
			{
				promptDialog.show(new AppDialogOK.IAppDialogOK()
				{
					@Override
					public void OnDialogCancel(DialogInterface iDialog)
					{
						SetToLoginActivity();
					}

					@Override
					public void OnOK_Click(DialogInterface iDialog)
					{
						SetToLoginActivity();
					}

				}, true);
				return;
			}
			
			SetToLoginActivity();
			return;
		}

		// Move back to the Stock Order Book display
		if (iResult.StatusCode.equals("3"))
		{
//			TradeAppInfo.ClearStockHistoryRecord();
			DismissWaitingDialog();
			if (promptDialog != null)
			{
				promptDialog.show(new IAppDialogOK()
				{
					@Override
					public void OnDialogCancel(DialogInterface iDialog)
					{
						CallBackToStockOrder();
					}

					@Override
					public void OnOK_Click(DialogInterface iDialog)
					{
						CallBackToStockOrder();
					}
				}, true);
			}
			else
				CallBackToStockOrder();
			return;
		}

		DismissWaitingDialog();
		// Prompt Error if there are one and do not know what to do
		if ((iResult.BrokerMessage != null)
				&& (iResult.BrokerMessage.length() != 0))
		{
			if (promptDialog != null)
				promptDialog.show(null, true);
		}
	}

	private void FlipToConfirmationDisplay()
	{
		String signText;
		int    textColor;
		
		int destChild = 1;
		// Display the information and ask for password
		String transType;
		TextView textViewObj;

		if (orderStockInfo.GetCurrencyCode().equals(TradeAppInfo.CNYCode))
		{
			signText = TradeAppInfo.CNYSign;
			textColor = getResources().getColor(R.color.DimYellow);
		}
		else if (orderStockInfo.GetCurrencyCode().equals(TradeAppInfo.USDCode))
		{
			signText = TradeAppInfo.USDSign;
			textColor = getResources().getColor(R.color.DimYellow);
		}
		else
		{
			signText = TradeAppInfo.HKDSign;
			textColor = getResources().getColor(R.color.White);
		}
		
		transType = orderStockInfo.getOrderSide();
		textViewObj = (TextView) findViewById(R.id.view_stocktrade_keypad_confirminfo_ActionText);
		if (transType.equals(Trade_StockReqOrderItem.TRANSACTIONTYPE_BID))
		{
			textViewObj.setTextColor(getResources().getColor(
					R.color.GreenBlue));
			textViewObj.setText(R.string.stockBuyText);
		}
		else
		{
			textViewObj.setTextColor(getResources().getColor(R.color.Red));
			textViewObj.setText(R.string.stockSellText);
		}

		((TextView) findViewById(R.id.view_stocktrade_keypad_confirminfo_Price))
				.setText(signText + orderStockInfo.getPiceText());
		((TextView) findViewById(R.id.view_stocktrade_keypad_confirminfo_Price))
				.setTextColor(textColor);
		
		((TextView) findViewById(R.id.view_stocktrade_keypad_confirminfo_Quantity))
				.setText(orderStockInfo.getOutStandingQuantityText());
		
		((TextView) findViewById(R.id.view_stocktrade_keypad_confirminfo_Amount))
				.setText(signText + orderStockInfo.getTotalText());
		((TextView) findViewById(R.id.view_stocktrade_keypad_confirminfo_Amount))
				.setTextColor(textColor);
		
		// Disable the click-able control
		ViewCtrlHelper.SetEnableRequestView(this,
				R.id.view_stocktrade_keypad_priceinfo_OptionBuy, false);
		ViewCtrlHelper.SetEnableRequestView(this,
				R.id.view_stocktrade_keypad_priceinfo_OptionSell, false);
		ViewCtrlHelper.SetEnableRequestView(this,
				R.id.view_stocktrade_keypad_header_Home, false);

		if (viewFlipObj.getDisplayedChild() == destChild)
			return;

		
		Animation animateAction;

		animateAction = AnimationUtils.loadAnimation(this, R.anim.just_delay);
		animateAction.setDuration(200);
		viewFlipObj.setOutAnimation(animateAction);

		animateAction = AnimationUtils.loadAnimation(this, R.anim.slide_up_in);
		animateAction.setDuration(200);
		animateAction.setAnimationListener(new AnimationListener()
		{
			@Override
			public void onAnimationEnd(Animation animation)
			{
				// Show the keyboard
				View editTextObj;

				editTextObj = (View) findViewById(R.id.view_stocktrade_keypad_confirminfo_Password);
				editTextObj.requestFocus();
			}

			@Override
			public void onAnimationRepeat(Animation animation)
			{	}

			@Override
			public void onAnimationStart(Animation animation)
			{	}
		});
		viewFlipObj.setInAnimation(animateAction);
		viewFlipObj.setDisplayedChild(destChild);
	}

	private void FlipToKeyPadEntry()
	{
		int destChild = 0;

		if (viewFlipObj.getDisplayedChild() == destChild)
			return;

		HideKeyBoard();

		// Release the click able control
		ViewCtrlHelper.SetEnableRequestView(this,
				R.id.view_stocktrade_keypad_priceinfo_OptionBuy, true);
		ViewCtrlHelper.SetEnableRequestView(this,
				R.id.view_stocktrade_keypad_priceinfo_OptionSell, true);
		ViewCtrlHelper.SetEnableRequestView(this,
				R.id.view_stocktrade_keypad_header_Home, true);

		Animation animateAction;
		animateAction = AnimationUtils.loadAnimation(this,
				R.anim.slide_down_out);
		animateAction.setDuration(200);
		viewFlipObj.setOutAnimation(animateAction);

		animateAction = AnimationUtils.loadAnimation(this, R.anim.just_delay);
		animateAction.setDuration(200);
		animateAction.setAnimationListener(new AnimationListener()
		{
			@Override
			public void onAnimationEnd(Animation animation)
			{
				// Clear the text
				((EditText) findViewById(R.id.view_stocktrade_keypad_confirminfo_Password))
						.setText("");
			}

			@Override
			public void onAnimationRepeat(Animation animation)
			{
			}

			@Override
			public void onAnimationStart(Animation animation)
			{
			}
		});
		viewFlipObj.setInAnimation(animateAction);
		viewFlipObj.setDisplayedChild(destChild);
	}

	@Override
	public void onBackPressed()
	{
		int viewId;

		viewId = viewFlipObj.getDisplayedChild();
		if (viewId == 1)
		{
			FlipToKeyPadEntry();
			return;
		}
		
		//Play cheapy on this
		int index;
		
		index = GetActivityController().GetCurrentClassIndex();
		if (index != 0)
		{
			Class<? extends Activity> prevClass;
			
			prevClass = GetActivityController().GetActivityClassOf(index-1);
			if (prevClass.equals(Trade_AcctComboActivity.class) || (prevClass.equals(Trade_StockInputActivity.class)))
			{
				super.onBackPressed();
				return;
			}					
		}
		
		//super.onBackPressed();
		CallBackToStockOrder();
	}

	private void SetCheckBoxState(int iResId, boolean isChecked)
	{
		CheckBox tgButton;

		// After the scroll, the highlight is always off
		tgButton = (CheckBox) findViewById(iResId);
		if (tgButton.isChecked() != isChecked)
			tgButton.setChecked(isChecked);
	}

	private void SetRadioButtonState(int iResId, boolean isChecked)
	{
		RadioButton rdButton;

		// After the scroll, the highlight is always off
		rdButton = (RadioButton) findViewById(iResId);
		if (rdButton.isChecked() != isChecked)
			rdButton.setChecked(isChecked);
	}

	private void SetStockTitleUpdate(String iCode, String iChnName,
			String iEngName)
	{
		TextView textViewObj;
		String stockName;

		textViewObj = (TextView) findViewById(R.id.view_stocktrade_keypad_header_Title);
		if (DeviceInfo.GetLanguageString().equals("lang_cht"))
			stockName = iChnName;
		else
			stockName = iEngName;

		textViewObj.setText(iCode + " " + stockName);
	}

	private void BlinkPriceInfo()
	{
		LinearLayout blinkObj;

		blinkObj = (LinearLayout) findViewById(R.id.view_stocktrade_keypad_priceinfo_CurPriceInfo);
		blinkObj.setBackgroundColor(getResources()
				.getColor(R.color.GreenGray));

		Animation animatAction = AnimationUtils.loadAnimation(
				actContext, R.anim.just_delay);
		animatAction.setDuration(invokeTimeDelay);
		animatAction.setAnimationListener(new AnimationListener()
		{
			@Override
			public void onAnimationEnd(Animation animation)
			{
				LinearLayout blinkObj;

				blinkObj = (LinearLayout) findViewById(R.id.view_stocktrade_keypad_priceinfo_CurPriceInfo);
				blinkObj.setBackgroundColor(actContext.getResources()
						.getColor(R.color.DarkerGray));
			}

			@Override
			public void onAnimationRepeat(Animation animation)
			{	}

			@Override
			public void onAnimationStart(Animation animation)
			{	}
		});
		blinkObj.startAnimation(animatAction);
	}

	private static final int	REFRESH_CONTENT	= 1;

	@Override
	public boolean onCreateOptionsMenu(Menu iMenu)
	{
		super.onCreateOptionsMenu(iMenu);
		if (TradeAppInfo.IsBMPMode() == false)
			return true;
		
		//Add the menu Item to the menu
		MenuItem menuItemObj = iMenu.add(0, REFRESH_CONTENT, Menu.NONE,
				R.string.updateText);
		menuItemObj.setIcon(R.drawable.ic_menu_lrefresh);
		menuItemObj.setShortcut('0', 'r');

		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem iMenu)
	{
		super.onOptionsItemSelected(iMenu);
		switch (iMenu.getItemId())
		{
			case REFRESH_CONTENT:
				if (isStockRequestStart == true)
					return true;
				if (curStockInfo.stockCode != null)
					StockQuoteRequest(Trade_StockFunctionTools.FormatFullStockCode(curStockInfo.stockCode));
				return true;
		}
		return false;
	}

	//Download Stock Request
	private void StockQuoteRequest(String iStockCode)
	{
		if (IsNetworkAvailable() == false)
		{
			ShowPromptMessage(getString(R.string.commErrorText));
			return;
		}

//		if (TradeAppInfo.HasSessionTimeExpired())
//		{
//			ShowTimeExpiredBox();
//			return;
//		}

		//Use min version to get data
		final TradeGetStockQuote quoteRequest;

		isStockRequestStart = true;		
		quoteRequest = new TradeGetStockQuote(actContext);
		quoteRequest.SetRequestQuoteInfo(appHost.IsDevelopment(), iStockCode, appHost.GetLSClient_AccountLogonName(), appHost.GetLSClient_SessionKey());
		quoteRequest.SendRequest(TradeAppInfo.IsDemoAccount(),
				new ITradeGetStockQuoteResponse()
				{
					@Override
					public void ResponseFunc(boolean iSuccessfulSend,
							TradeGetStockQuoteResult iResponse)
					{
						isStockRequestStart = false;						
						quoteRequest.Dispose();						
						if (iSuccessfulSend == false)
						{
							ShowPromptMessage(getString(R.string.commErrorText));
							return;
						}

						if (!iResponse.resultCode.equals("0"))
						{
							String textValue;
							
							textValue = iResponse.errorMessage;
							if (textValue.equals(""))
								textValue = getString(R.string.commErrorText);
							ShowPromptMessage(textValue);	
							if (iResponse.resultCode.equals("-1"))
								appHost.LS_Client_ResetConnection();							
							return;
						}
						
						Trade_StockViewInfoItem updateItem;
						
						updateItem = iResponse.stockQuoteItem;
						if (updateItem != null)
						{
							//Just Update the information we need							
							if (updateItem.GetCurAskPriceText().equals("") == false)
								curStockInfo.SetAskPrice(updateItem.GetCurAskPriceText());
							
							if (updateItem.GetCurBidPriceText().equals("") == false)
								curStockInfo.SetBidPrice(updateItem.GetCurBidPriceText());
							
							if (updateItem.GetCurPriceText().equals("") == false)
								curStockInfo.SetCurPrice(updateItem.GetCurPriceText(), true);
							else
								curStockInfo.SetCurPrice(curStockInfo.GetCurPriceText(), true);
						}
						DismissWaitingDialog();						
						UpdateNewStockInfo(curStockInfo);
					}
				});
	}

	private void UpdateNewStockInfo(Trade_StockViewInfoItem iStockItem)
	{
		// This is for the viewing Start
		// Set to the top display
		SetStockCurBidAsk(iStockItem);
		UpdateStockPriceUI(iStockItem, true);

		UpdateToast(getString(R.string.stockQuoteUpdateText));
	}
	
	private final String[] reqSchema = { "Nominal", "Net", "NetPercentage",
								  "BidPrice","AskPrice"};
	
	private String reqIDString = null;
	private void SubscribeViewingStock( String iStockCode)
	{
		LS_SubscriptionItem interestItem;
	
		if(reqIDString == null)
			reqIDString = LSGetUniqueID();
		
		interestItem = new LS_SubscriptionItem("TELETEXT");
		interestItem.AddSubscribeItem(iStockCode);
		interestItem.SetSubscribeSchema(reqSchema);						
		/* Register as a free type */
		if (LightStreamerSubscribeItem(reqIDString, interestItem, LS_ItemRequestType.NONE, this) == false)
		{
			reqIDString = null;
			//Message for not being successful			
			ShowPromptMessage(getString(R.string.SubscribeError_Text));
			return;
		}
	}
	
	@Override
	public void onUpdate(String iIdentifier, int iSchemaIndex,
			String iSchemaValue, UpdateInfo iUpdateInfo)
	{
		String tmpValue, tmpValue2, tmpValue3;
								
		/* Consider as a fail */
		tmpValue = iUpdateInfo.getNewValue("Nominal");
		if ((tmpValue == null) || (tmpValue.length() == 0))
			return;
		
		if (curStockInfo == null)
			return;
		
		tmpValue2 = iUpdateInfo.getNewValue("BidPrice");		
		tmpValue3 = iUpdateInfo.getNewValue("AskPrice");		
		curStockInfo.SetPriceInfo(tmpValue, tmpValue2, tmpValue3, false);
						
		tmpValue = iUpdateInfo.getNewValue("Net");
		tmpValue2 = iUpdateInfo.getNewValue("NetPercentage");
		curStockInfo.SetNetDiffPrice(tmpValue, tmpValue2);

		if (debugMode)
			TDStockLog.i(GetIdentity(), curStockInfo.toString());		
		
		Runnable runObject = new Runnable()
		{
			public void run()
			{
				SetStockCurBidAsk(curStockInfo);
				UpdateStockPriceUI(curStockInfo, true);
			}
		};
		UIHandler.post(runObject);
		
	}

	@Override
	public void ReporterTicker_Response(int iRemainSecond)
	{
		/* This is not a charge type, we do not need to look at it */	
	}

	@Override
	public void LS_UserClient_ConnectionReport(CONNECTION_STATUS iStatus)
	{		
		if (TradeAppInfo.IsDemoAccount() || TradeAppInfo.IsBMPMode())
			return;
	
		if (debugMode)
			TDStockLog.i(GetIdentity(), "*** Activity Check Status=" + iStatus);

		//Return to the sign in message display for the application
		if (iStatus == CONNECTION_STATUS.CLOSE_BY_FORCE)
		{
			SetToAppLoginActivity();
			return;	
		}
		
		boolean isConnected;
		
		if (iStatus == CONNECTION_STATUS.CONNECTED)
			isConnected = true;
		else
			isConnected = false;
		
		if (TradeAppInfo.IsBMPMode() == false)
			findViewById(R.id.view_stocktrade_keypad_header_informer).setEnabled(isConnected);

		//Set a dummy ui to the display
		if (isConnected)
			DetachedDisconnectMessage();
		else
		{
			DismissWaitingDialog();			
			AttachDisconnectMessage();
		}
	}

	private PopupWindow lsStatusPopupView = null;
	private View        viewObj = null;
	private Runnable popupWindow_runnable = null;	
	private void AttachDisconnectMessage()
	{
		if (lsStatusPopupView == null)
		{
			LayoutInflater inflatObj = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			
			viewObj  = inflatObj.inflate(R.layout.trade_prompt_msgbox, null);
			viewObj.findViewById(R.id.prompt_msgboxContent).setOnClickListener( new OnClickListener()
								{
									@Override
									public void onClick(View arg0)
									{
										boolean status;
										
										status = appHost.LSClient_Connect(new ILS_UserClient_Authentication_Report()
										{
											@Override
											public void LS_UserClient_Authentication_Response(
													LS_UserClient_Authentication_Result iResponse)
											{
												if ((iResponse.successfulSend == false) || (iResponse.statusCode == null) 
													|| !iResponse.statusCode.equals("0"))
												{
													UIHandler.postDelayed(popupWindow_runnable, Trade_AppConstant.timeDelayForPopup);
													return;
												}												
											}											
										});											
										if (status == true)
											DetachedDisconnectMessage();
									}
								});
			
			lsStatusPopupView = new PopupWindow(viewObj, 
									 LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
			lsStatusPopupView.setAnimationStyle(R.anim.zoom_enter);
			lsStatusPopupView.setOutsideTouchable(true);	
		}
		
		if (!lsStatusPopupView.isShowing())
		{
			if (popupWindow_runnable == null)
			{
				popupWindow_runnable = new Runnable()
				{
					public void run()
					{
						lsStatusPopupView.showAtLocation(viewObj, Gravity.BOTTOM|Gravity.CENTER_HORIZONTAL,
												    0, Trade_AppConstant.popupHeightAboveLoc);
					};
				};
			}
			UIHandler.postDelayed(popupWindow_runnable, Trade_AppConstant.timeDelayForPopup);				
		}			
	}		
	
	private void DetachedDisconnectMessage()
	{
		if (lsStatusPopupView == null)
			return;
		
		if (popupWindow_runnable != null)
			UIHandler.removeCallbacks(popupWindow_runnable);
		
		if (lsStatusPopupView.isShowing())
			lsStatusPopupView.dismiss();
	}
	
	private AppDialogOK promptMessage = null;
	private void ShowPromptMessage(String iContent)
	{
		if (promptMessage != null)
			promptMessage.dismiss();
		
		DismissWaitingDialog();
		promptMessage = ShowInfoBox(iContent);
	}
	
}
